package spider.mutithread;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadPool {
	private static ExecutorService metaSearchPool;
	private static ExecutorService spiderPool;

	static {
		metaSearchPool = new ThreadPoolExecutor(30, 50, 60l, TimeUnit.SECONDS,
				new ArrayBlockingQueue<Runnable>(10),
				new ThreadPoolExecutor.AbortPolicy());
		spiderPool = new ThreadPoolExecutor(25, 75, 60l, TimeUnit.SECONDS,
				new ArrayBlockingQueue<Runnable>(10),
				new ThreadPoolExecutor.AbortPolicy());
	}
	
	public static void runMetaThreadWithoutBlocking(Runnable r) throws RejectedExecutionException
	{
		metaSearchPool.execute(r);
		return;
	}
	
	public static void runMetaThread(Runnable r)
	{
		while (true)
		{
			try{
				metaSearchPool.execute(r);
				return;
			}catch (RejectedExecutionException rj)
			{
				try{
					Thread.sleep(1000);
				}catch (InterruptedException ie)
				{
					
				}
			}
		}
	}
	
	public static void runSpiderThreadWithoutBlocking(Runnable r) throws RejectedExecutionException
	{
		spiderPool.execute(r);
		return;
	}
	
	public static void runSpiderThread(Runnable r)
	{
		while (true)
		{
			try{
				spiderPool.execute(r);
				return;
			}catch (RejectedExecutionException rj)
			{
				try{
					Thread.sleep(1000);
				}catch (InterruptedException ie)
				{
					
				}
			}
		}
	}

}
